package com.simon.netty.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by changf on 2017/7/14.
 */
public class EchoClientHandler   extends SimpleChannelInboundHandler<ByteBuf>{

    //客户端连接服务器后被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client connecting server");
        byte[] req="QUERY ORDER".getBytes();
        ByteBuf message= Unpooled.buffer(req.length);
        message.writeBytes(req);
        ctx.writeAndFlush(message);
    }

    //从服务器接受数据后调用
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {


        System.out.println("client read data from server");
        byte[] buf=new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(buf);
        String body=new String(buf,"UTF-8");
        System.out.println("client get data:"+body);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("client exception:"+cause.getMessage());
        ctx.close();
    }

}
